#include <bits/stdc++.h>
#include <pthread.h>//linux 使用线程，需要 -lpthread
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>
#include "LockGuard.hpp"
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;


int tickets = 1000;



void* threadRoutine(void* args)
{
    while(1)
    {
        {
            LockGuard local_mutex(g_mutex);
            if (tickets > 0)
            {
                usleep(1000);
                cout << (char *)args << "抢到票.票剩余：" << --tickets << "\n";
            }
            else
            {
                cout << (char*)args<<"没票了\n";
                pthread_cond_wait(&cond, &g_mutex);
            }
        }
    }
}


int main()
{
    
    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, threadRoutine,(void*)"thread-1" );
    pthread_create(&t2, nullptr, threadRoutine,(void*)"thread-2" );
    pthread_create(&t3, nullptr, threadRoutine,(void*)"thread-3" );

    sleep(2);
    while (1)
    {
        
        // pthread_cond_broadcast(&cond);//唤醒所有线程
        sleep(5);
        if (tickets <= 0)
        {
            LockGuard local_lock(g_mutex);
            //补票
            tickets += 1000;
            pthread_cond_signal(&cond);//唤醒最近的那个线程
        }
    }

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_mutex_destroy(&g_mutex);
    pthread_cond_destroy(&cond);
    return 0;
}